<?php

namespace plugin\admin\app\controller;

use app\traits\DataProcessor;
use plugin\admin\app\common\Auth;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\BannerPosition;
use plugin\admin\app\model\Page;
use support\Request;
use support\Response;
use plugin\admin\app\model\Banner;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 广告列表 
 */
class BannerController extends Crud
{
    use DataProcessor;
    
    /**
     * @var Banner
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new Banner;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('banner/index');
    }

    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $query = $this->doSelect($where, $field, $order);
        $list = $this->doFormat($query, $format, $limit);
        return $list;
    }

    protected function formatNormal($items, $total): Response
    {
        $banners = BannerPosition::list();

        $banners = array_combine(
            array_column($banners, 'value'),
            array_column($banners, 'name')
        );

        $pages = Page::all()->toArray();

        foreach ($items as $key=>$item) {
            $item = json_decode(json_encode($item), true);
            $links = explode('?', $item['link']);

            $item['link'] = $links[0];

            $newParams = [];
            foreach ($pages as $page) {
                if ($page['path'] == $item['link']) {
                    $newParams = explode(',', $page['params']);
                    break;
                }
            }

            $newParams = array_filter($newParams);

            $params = !empty($links[1]) ? explode('&', $links[1]) : [];
            $item['params'] = [];

            foreach ($newParams as $newParam) {
                $item['params'][$newParam] = '';
                foreach ($params as $param) {
                    [$paramKey, $paramValue] = explode('=', $param);

                    if ($newParam == $paramKey) {
                        $item['params'][$paramKey] = $paramValue;
                        break;
                    }
                }
            }

            $item['position_text'] = $banners[$item['position_id']];
            $item['is_show_text'] = $item['is_show'] ? '是': '否';

            $items[$key] = $item;
        }

        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }

    protected function insertInput(Request $request): array
    {
        $original = $request->post();
        $data = $this->inputFilter($request->post());
        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            $data[$password_filed] = Util::passwordHash($data[$password_filed]);
        }

        if (!Auth::isSupperAdmin() && $this->dataLimit) {
            if (!empty($data[$this->dataLimitField])) {
                $admin_id = $data[$this->dataLimitField];
                if (!in_array($admin_id, Auth::getScopeAdminIds(true))) {
                    throw new BusinessException('无数据权限');
                }
            }
        }

        if (!empty($original['params'])) {
            $data['link'] .= '?' . http_build_query($original['params']);
        }

        DataProcessor::processSwitch($data, 'is_show');


        return $data;
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            try {
                $this->checkData($request);
            } catch (\Exception $e) {
                return $this->json(400, $e->getMessage());
            }
            return parent::insert($request);
        }
        return view('banner/insert');
    }



    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            try {
                $this->checkData($request, false);
            } catch (\Exception $e) {
                return $this->json(400, $e->getMessage());
            }
            return parent::update($request);
        }
        return view('banner/update');
    }

    protected function updateInput(Request $request): array
    {
        $original = $request->post();
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        if (!Auth::isSupperAdmin() && $this->dataLimit && !empty($data[$this->dataLimitField])) {
            $admin_id = $data[$this->dataLimitField];
            if (!in_array($admin_id, Auth::getScopeAdminIds(true))) {
                throw new BusinessException('无数据权限');
            }
        }
        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            // 密码为空，则不更新密码
            if ($data[$password_filed] === '') {
                unset($data[$password_filed]);
            } else {
                $data[$password_filed] = Util::passwordHash($data[$password_filed]);
            }
        }

        if (!empty($original['params']) && count($original['params']) > 0) {
            $data['link'] .= '?' . http_build_query($original['params']);
        }

        DataProcessor::processSwitch($data, 'is_show');
        unset($data[$primary_key]);
        return [$id, $data];
    }

    protected function checkData($request, $isInsert = true)
    {
        $positionId = $request->post('position_id');
        if (!is_numeric($positionId) || $positionId <= 0) {
            throw new \Exception('不正确的广告位置');
        }

        $imgUrl = $request->post('img_url');
        if ($imgUrl == '') {
            throw new \Exception('图片地址不能为空');
        }

        if ($isInsert) {
            $positionInfo = BannerPosition::find($positionId);
            if ($positionInfo['allowed_count'] != -1 && Banner::where('position_id', $positionId)->count() >= $positionInfo['allowed_count']) {
                throw new \Exception('该广告位广告已达上限');
            }
        }

    }
}
